package com.dsg.controller.oil;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dsg.aspect.NoRepeatSubmit;
import com.dsg.common.constants.MessageConstants;
import com.dsg.common.dto.AjaxResult;
import com.dsg.common.util.BeanKit;
import com.dsg.common.util.SingletonLoginUtils;
import com.dsg.common.util.UUIDGenerator;
import com.dsg.common.util.toolbox.DateUtil;
import com.dsg.common.util.toolbox.StringUtil;
import com.dsg.controller.base.BaseController;
import com.dsg.entity.apply.DsgApplyBill;
import com.dsg.entity.apply.DsgApplyCard;
import com.dsg.entity.apply.DsgApplyStatus;
import com.dsg.entity.dto.OilLimitDto;
import com.dsg.entity.oil.DsgOilLimit;
import com.dsg.service.apply.IDsgApplyBillService;
import com.dsg.service.apply.IDsgApplyCardService;
import com.dsg.service.apply.IDsgApplyStatusService;
import com.dsg.service.oil.IDsgOilLimitService;
import com.dsg.util.Constant;
import com.dsg.workflow.WorkflowEngine;
import com.powerbridge.core.util.toolbox.CollectionUtil;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * <p>
 * 油咭限额 前端控制器
 * </p>
 *
 * @author system
 * @since 2020-07-28
 */
@RestController
@RequestMapping("/oil/dsgOilLimit")
public class DsgOilLimitController extends BaseController {

    @Autowired
    private IDsgOilLimitService service;
    @Autowired
    private IDsgApplyCardService cardService;
    @Autowired
    private IDsgApplyStatusService statusService;
    @Autowired
    private IDsgApplyBillService billService;
    @Autowired
    private WorkflowEngine engine;

    @GetMapping(value = "/viewLimit")
    @ApiOperation("更改油咭限額")
    @ApiResponses({
            @ApiResponse(response = OilLimitDto.class, code = 1, message = "ok")
    })
    public AjaxResult viewLimitEsso(String cardOid) {
        DsgApplyCard card = cardService.getById(cardOid);
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("OIL_COM", card.getOilCom());
        wrapper.eq("ENT_CODE", getEntCode());
        List<DsgOilLimit> limitList = service.list(wrapper);

        OilLimitDto dto = service.getOilLimitSum(cardOid);
        if (card != null && CollectionUtil.isNotEmpty(limitList)) {
            dto.setSelectedLimit(card.getLimitId());
        }
        dto.setLimitList(limitList);

        return success(dto);
    }

//    @GetMapping(value = "/viewLimitCaltex")
//    @ApiOperation("更改油咭限額-查看(Caltex)")
//    @ApiResponses({
//            @ApiResponse(response = OilLimitDto.class, code = 1, message = "ok")
//    })
//    public AjaxResult viewLimitCaltex(String carOid) {
//        QueryWrapper wrapper = new QueryWrapper();
//        wrapper.eq("OIL_COM", DsgOilLimit.OIL_COM_CALTEX);
//        wrapper.eq("ENT_CODE", getEntCode());
//        List<DsgOilLimit> limitList = service.list(wrapper);
//
//        wrapper = new QueryWrapper();
//        wrapper.eq("CAR_ID", carOid);
//        wrapper.isNotNull("LIMIT_ID");
//        DsgApplyCard card = cardService.getOne(wrapper, false);
//
//        OilLimitDto dto = service.getOilLimitSum(carOid);
//        if (card != null && StringUtil.isNotEmpty(card.getLimitId()) && CollectionUtil.isNotEmpty(limitList)) {
//            List<String> currlimitOidList = Arrays.asList(card.getLimitId().split(","));
//            wrapper = new QueryWrapper();
//            wrapper.in("OID", currlimitOidList);
//            wrapper.orderByAsc("CALTEX_TYPE");
//            List<DsgOilLimit> currlimitList = service.list(wrapper);
//            dto.setCurrlimitList(currlimitList);
//        }
//        dto.setLimitList(limitList);
//
//        return success(dto);
//    }

    @PutMapping(value = "/changeOilLimit")
    @ApiOperation("更改油咭限額-更改")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult changeOilLimit(String cardOid, String remark, String limit1, String limit2, String limit3, String limit4) throws Exception {
        String limit = limit1;
        String oilCom = DsgOilLimit.OIL_COM_ESSO;
        Set<String> newLimit = new HashSet<>();
        if (StringUtil.isNotEmpty(limit1) && StringUtil.isNotEmpty(limit2) && StringUtil.isNotEmpty(limit3) && StringUtil.isNotEmpty(limit4)) {
            limit = String.format("%s,%s,%s,%s", limit1, limit2, limit3, limit4);
            oilCom = DsgOilLimit.OIL_COM_CALTEX;
            newLimit.addAll(Arrays.asList(limit.split(",")));
        } else if (StringUtil.isNotEmpty(limit1)){
            newLimit.add(limit);
        } else {
            return fail("限額不能全為空");
        }

        DsgApplyCard card = cardService.getById(cardOid);
        if (DsgApplyCard.LIMIT_STATUS_0 == card.getLimitStatus()) {
            return fail("上次提交的油咭限額修改請求還沒有生效，還不能再次修改");
        }
        if (!oilCom.equals(card.getOilCom())) {
            return fail("oilCom不正確或限額個數不正確");
        }
        if (StringUtil.isNotEmpty(card.getLimitId())) {
            Set<String> oldLimit = new HashSet<>();
            oldLimit.addAll(Arrays.asList(card.getLimitId().split(",")));
            if (oldLimit.containsAll(newLimit)) {
                return fail("油咭限額跟原來的一樣，請重新選擇");
            }
        }

        card.setLimitId(limit);
        card.setRemark(remark);
        card.setLimitStatus(DsgApplyCard.LIMIT_STATUS_0);
        cardService.updateById(card);

        DsgApplyBill bill = billService.getBillByCard(cardOid);
        bill.setOid(UUIDGenerator.getUUID());
        String appNo = DateUtil.format(new Date(), "yyyyMMddHHmmss");
        bill.setAppNo(appNo);
        bill.setPayType(Constant.PAY_TYPE_ATP);
        bill.setAppType(DsgApplyBill.APP_TYPE_12);
        bill.setApplyTime(new Date());
        BeanKit.resetCommonField(bill);
        billService.save(bill);

        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("CARD_ID", cardOid);
        DsgApplyStatus status1 = statusService.getOne(wrapper, false);
        DsgApplyStatus status = new DsgApplyStatus();
        status.setOid(UUIDGenerator.getUUID());
        status.setAppStatus(DsgApplyStatus.APP_STATUS_DRAFT);
        status.setAppNo(appNo);
        status.setCardId(cardOid);
        status.setCarNo(status1.getCarNo());
        status.setAppType(DsgApplyBill.APP_TYPE_12);
        statusService.save(status);
        engine.begin(bill);
        return success();
    }

    /**
     * 查询列表（分页）
     *
     * @param dsgOilLimit
     * @return
     */
    @GetMapping(value = "/list")
    @ApiOperation("查询列表（分页）")
    public AjaxResult list(DsgOilLimit dsgOilLimit) {
        // 分页
        Page page = getPage();
        String sort = getParameter("sort");
        List<OrderItem> orderItemList = new ArrayList<>();
        OrderItem orderItem = new OrderItem();
        if (StringUtil.isEmpty(sort)) {
            orderItem.setColumn("CREATE_TIME");
            orderItem.setAsc(false);
            orderItemList.add(orderItem);
            page.setOrders(orderItemList);
        }
        dsgOilLimit.setEntCode(SingletonLoginUtils.getSystemEntCode());
        page = service.selectByList(page, dsgOilLimit);
        // 格式要返回的数据
        AjaxResult ajaxResult = json(MessageConstants.SSO_STATUS_SUCCESS, page.getRecords(), (int) page.getTotal());
        return ajaxResult;
    }

    /**
     * 新增
     *
     * @param dsgOilLimit
     * @return
     */
    @NoRepeatSubmit
    @PostMapping(value = "/add")
    @ApiOperation("新增")
    public AjaxResult add(@RequestBody DsgOilLimit dsgOilLimit) {
        dsgOilLimit.setOid(UUIDGenerator.getUUID());
        boolean flag = service.save(dsgOilLimit);
        if (flag) {
            return result(MessageConstants.SSO_STATUS_SUCCESS);
        } else {
            return result(MessageConstants.SSO_STATUS_FAIL);
        }
    }

    /**
     * 更新
     *
     * @param dsgOilLimit
     * @return
     */
    @NoRepeatSubmit
    @PutMapping(value = "/update")
    @ApiOperation("更新")
    public AjaxResult update(@RequestBody DsgOilLimit dsgOilLimit) {
        AjaxResult ajaxResult;
        boolean flag = service.updateById(dsgOilLimit);
        if (flag) {
            ajaxResult = json(MessageConstants.SSO_STATUS_SUCCESS, dsgOilLimit);
        } else {
            ajaxResult = result(MessageConstants.SSO_STATUS_FAIL);
        }
        return ajaxResult;
    }

    /**
     * 批量删除
     *
     * @return
     */
    @DeleteMapping(value = "/delete")
    @ApiOperation("批量删除")
    public AjaxResult delete(@ApiParam(value = "id以，号分隔", name = "idList", required = true) @RequestParam String idList) {
        Boolean flag = service.removeByIds(Arrays.asList(idList.split(",")));
        if (flag) {
            return result(MessageConstants.SSO_STATUS_SUCCESS);
        } else {
            return result(MessageConstants.SSO_STATUS_FAIL);
        }
    }
}
